<?php

/* @var $this \yii\web\View */
/* @var $content string */

use yii\helpers\Html;
use front\assets\AppAsset;
use yii\helpers\Url;
?>
<div class="m-bar" id="J_actBtn">
    <a href="javascript:;">全选</a>
</div>

<div class="m-list" id="J_forList">

    <!--购物车循环开始-->
    <?php foreach($list as $k=>$v){?>
    <div class="u-list">
        <a href="javascript:;" class="u-slt J_sltBtn">&nbsp;</a>
        <a href="<?= Url::to(['product/detail','pid' => $v['product_id']])?>"><img src="<?php echo $v['data']['thumb'][0]?>"/></a>
        <h6 data-pid="<?php echo $v['product_id'];?>"><a href="<?= Url::to(['product/detail','pid' => $v['product_id']])?>
"><b><?php if(isset($v['data']['goods_price']['name'])){echo $v['data']['goods_price']['name'];}?></b><br /><?php echo $v['data']['item_attrText_map'];?></a></h6>
        <h5 data-oid="<?php echo $v['product_id'];?>,<?php echo $v['shop_id'];?>"><a href="javascript:;" data-type="subt">-</a><u><?php echo $v['num'];?></u><a href="javascript:;" data-type="plus">+</a></h5>
        <em>￥ <b class="J_price"><?php print_r($v['data']['goods_price']);?></b></em>
    </div>
    <?php } ?>
    <!--购物车循环结束-->

</div>

<div class="m-total" id="J_total">
    <span>总计：<b>￥0.00</b>  <small>（x<i>0</i>）</small></span>
    <a href="javascript:;" class="J-delcart">删除</a>
    <form action="/web/order/buy" method="post" id="form">

    </form>
    <a href="javascript:;" class="setProductBuy">结算</a>
</div>

<div class="m-nav f-cb" id="">
    <a href="/web/default/home">首页</a>
    <a href="/web/category/category-list?shop_id=1001">分类</a>
    <a href="javascript:;" class="z-on">购物车</a>
    <a href="/web/my">我的</a>
</div>

<script>
    $(function(){
        // 订单ID
        var oId = [];

        var zon = 'z-on', total = $('#J_total');
        var sltBtn = $('#J_actBtn a').eq(0);

        // 全选
        sltBtn.on('touchend', function(evt){

            var _that = $(this), _child = $('.J_sltBtn');

            oId = [];

            if(_that.hasClass(zon)){

                _that.removeClass(zon);
                _child.removeClass(zon);
                total.find('a').removeClass(zon);

                total.find('b').text('￥0.00');
                total.find('i').text('0');

            }else{

                _that.addClass(zon);
                _child.addClass(zon);
                total.find('a').addClass(zon);

                var _pids = [], _nums = [];
                _child.each(function(){
                    oId.push($(this).parent().find('h5').eq(0).attr('data-oid'));
                    _pids.push($(this).parent().find('h6').eq(0).attr('data-pid'));
                    _nums.push($(this).parent().find('u').text());
                });

                if(_pids.length > 0){

                    _pids = _pids.join(',');
                    _nums = _nums.join(',');

                    // 计算总价
                    $.ajax({ url: "<?=url::to('submitcount')?>", dataType:'jsonp', data:{'pids':_pids, 'nums': _nums}, timeout:5000,

                        success: function(_info){
                            total.find('b').text('￥' + _info['total']);
                            total.find('i').text(_info['count1']);
                        }
                    });
                }
            }

            console.log(oId);
            setProductOrder(oId);
            delCart(oId);
            evt.preventDefault();
            return false;
        });

        // 加减
        var cartList = $('#J_forList'), _lock = 'z-lock';
        cartList.find('h5').on('touchend', 'a', function(){

            var _that = $(this);
            if(_that.hasClass(_lock)) return false;

            // 锁定
            _that.addClass(_lock);

            var _type = _that.attr('data-type'),
                _id = _that.parent().prev().attr('data-pid');


            if(_type === 'subt'){
                var _then = parseFloat(_that.next().text());
                var _editthen = _then-1;
            }else{
                var _then = parseFloat(_that.prev().text());
                var _editthen = _then+1;
            }

            if(_type === 'subt' && _then === 1){

                _that.removeClass(_lock);

                return false;
            }

            var _parent = _that.closest('div'), isSlt = _parent.find('a').eq(0).hasClass(zon);

            // 请求数据
            $.ajax({ url: "<?=url::to('submitnum')?>", dataType:'jsonp', data:{'id':_id,'oId':oId,'num':_editthen}, timeout:5000,

                success: function(_info) {

                    var _min = _info['min'], _max = _info['max'], _price = _info['price'];

                    if(_type === 'plus' && _then >= _max){

                        _that.removeClass(_lock);

                        return false
                    }

                    // 是否关联总价
                    if(isSlt){
                        var _total = parseFloat(total.find('b').eq(0).text().substring(1)),
                            _count = parseInt(total.find('i').eq(0).text(), 10);
                        if(_type === 'subt'){

                            total.find('b').eq(0).text('￥' + (_total - _price));
                            total.find('i').text(_count - 1);

                        }else{

                            total.find('b').eq(0).text('￥' + (_total + _price));
                            total.find('i').text(_count + 1);
                        }
                    }

                    // 减法
                    if(_type === 'subt'){

                        _that.next().text(--_then);

                    }else{

                        _that.prev().text(++_then);

                    }

                    // 解锁
                    _that.removeClass(_lock);
                }
            });
        });

        // 单选
        cartList.on('touchend', '.J_sltBtn', function(evt){

            var _that = $(this),
                _parent = _that.closest('div'),
                _id = _parent.find('h6').attr('data-pid'),
                _oid = _parent.find('h5').attr('data-oid');

            var _act = 1; // 加
            if(_that.hasClass(zon)){

                _act = 0; // 减

                _that.removeClass(zon);
                oId = delSub(oId, _oid);

                if(oId.length <= 0){
                    total.find('a').removeClass(zon);
                    sltBtn.removeClass(zon);
                }

            }else{

                _that.addClass(zon);
                oId.push(_oid);

                if(oId.length <= 1) total.find('a').addClass(zon);
            }

            // 计算总价
            $.ajax({ url: "<?=url::to('submit')?>", dataType:'jsonp', data:{'id':_id}, timeout:5000,

                success: function(_info){
                    console.info(_info);
                    var _num = parseInt(_parent.find('u').text(), 10),
                        _total = parseFloat(total.find('b').eq(0).text().substring(1)),
                        _count = parseInt(total.find('i').eq(0).text(), 10);

                    total.find('b').text('￥' + (_act ? (_total + _info['price'] * _num) : (_total - _info['price'] * _num)));
                    total.find('i').text(_act ? (_count + _num) : (_count - _num));
                }
            });

            console.log(oId);
            setProductOrder(oId);
            delCart(oId);
            evt.preventDefault();
            return false;
        });

    });

    // 删除重复项目
    function delSub(arr, a){
        var ret = [];
        for(var i in arr){ if(arr[i] != a) ret.push(arr[i]); }
        return ret;
    }

    /**
     * 删除购物车商品
     */
    function delCart(oId){
        var html=[];
        $(".J-delcart").click(function(){
            if($(this).hasClass('z-on')){
                $.each(oId,function(k,v){
                    html.push(v);
                })

                $.get("<?=url::to('delete')?>",{oid:html},function(data){
                   if(data.status==1){
                       alert(data.message);
                       location.reload();
                   }else{
                       alert(data.message);
                   }
                },'jsonp');
            }
        })
    }


    /**
     *提交到购买页面
     */
    function setProductOrder(oId){
        if(oId){
            var html='';
            $(".setProductBuy").click(function(){
                if($(this).hasClass('z-on')){
                    $.each(oId,function(k,v){
                        html+='<input type="hidden" id="retailerId" name="retailerId['+k+']" value="'+v+'">';
                    })
                    $("#form").append(html);
                    $("#form").submit();
                }
            })
        }

    }

</script>
